﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using CodeGenerate;
using System.IO;
using CodeGenerate.Data;
using CodeGenerate.TemplateEngine;
using System.Data;
using System.Configuration;

namespace CodeGenerate
{
    public class DataBaseService : IDataBase
    {
        public class Template
        {
            public const string AllModel = "AllModel.config";
            public const string AllProc = "Allproc.config";
            public const string AllStruct = "AllStruct.config";
            public const string Aspx = "aspx.config";
            public const string AspxEdit = "aspxEdit.config";
            public const string AspxList = "aspxList.config";
            public const string AspxQuery = "aspxQuery.config";
            public const string AspxInfo = "aspxInfo.config";
            public const string AspxCs = "aspxcs.config";
            public const string AspxCsEdit = "aspxcsEdit.config";
            public const string AspxCsInfo = "aspxcsInfo.config";
            public const string AspxCsQuery = "aspxcsQuery.config";
            public const string AspxCsSave = "aspxcsSave.config";
            public const string BussinessImplement = "bussinessImplement.config";
            public const string ServiceCmdObject = "serviceCmdObject.config";
            public const string ServicePageList = "servicePageList.config";
            public const string Datacontract = "datacontract.config";
            public const string Dataexchange = "dataexchange.config";
            public const string AspxDesignerCs = "aspxdesignercs.config";
            public const string ServiceContract = "serviceContract.config";
            public const string ServiceImplement = "ServiceImplement.config";
            public const string CoreService = "CoreService.config";
            public const string IocConfig = "IocConfig.config";
        }


        //private string connstr = "server=.;database=busquery;uid=sa;pwd=sa";
        private string connstr
        {
            get
            {
                return System.Configuration.ConfigurationManager.AppSettings["ConnString"].ToString();
            }
        }
        #region IDataBase 成员

        public List<Table> GetObjects(ObjectType type)
        {
            return DataOperate.GetObject(connstr, type);
        }

        public List<Column> GetColumns(string tableName)
        {
            return ColumnUtil.GetColumns(connstr, tableName);

        }

        #region IDataBase 成员


        /// <summary>
        /// 获取视图列信息
        /// </summary>
        /// <param name="viewName"></param>
        /// <param name="type"></param>
        /// <returns></returns>
        public List<Column> GetViewColumns(string viewName)
        {
            return ColumnUtil.GetViewColumns(connstr, viewName);
        }

        #endregion

        public List<StoredProcedureParam> GetParas(string procName)
        {
            return StoredProcedureUtil.GetStoredProcedureParam(connstr, procName);
        }

        #endregion

        private string GetTemplateDir()
        {
            return ConfigurationManager.AppSettings["TemplatePath"] + @"\Template\";
        }


        #region IDataBase 成员

        private void WriteLog(string msg)
        {
            string path = string.Format(@"{0}\logs\{1}.config", ConfigurationManager.AppSettings["TemplatePath"], DateTime.Now.ToString("yyyy-MM-dd"));
            if (!Directory.Exists(Path.GetDirectoryName(path)))
            {
                Directory.CreateDirectory(Path.GetDirectoryName(path));
            }
            using (StreamWriter sw = new StreamWriter(path, true, Encoding.Default))
            {
                sw.WriteLine(string.Format("{0}:{1}", DateTime.Now, msg));
                sw.WriteLine();
            }
        }

        private string WrongMsg = string.Format("{0}：服务不可用", DateTime.Now);

        public string CreateAllModel()
        {
            string result = string.Empty;
            try
            {
                TemplateManager tm = TemplateManager.FromFile(string.Format("{0}{1}", GetTemplateDir(), Template.AllModel));
                result = tm.Process();
            }
            catch (Exception ex)
            {
                result = WrongMsg;
                WriteLog("CreateAllModel \t" + ex.Message);
            }
            return result;
        }

        public string CreateAllProc()
        {
            string result = string.Empty;
            try
            {
                TemplateManager tm = TemplateManager.FromFile(string.Format("{0}{1}", GetTemplateDir(), Template.AllProc));
                result = tm.Process();
            }
            catch (Exception ex)
            {
                result = WrongMsg;
                WriteLog("CreateAllProc \t" + ex.Message);
            }
            return result;
        }

        public string CreateAllStruct()
        {
            string result = string.Empty;
            try
            {
                TemplateManager tm = TemplateManager.FromFile(string.Format("{0}{1}", GetTemplateDir(), Template.AllStruct));
                result = tm.Process();
            }
            catch (Exception ex)
            {
                result = WrongMsg;
                WriteLog("CreateAllStruct \t" + ex.Message);
            }
            return result;
        }

        public string CreateAspx(Table table)
        {
            string result = string.Empty;
            try
            {
                TemplateManager tm = TemplateManager.FromFile(string.Format("{0}{1}", GetTemplateDir(), Template.Aspx));
                tm.SetValue("table", table);
                //tm.SetValue("columns",GetColumns(table.Name));
                result = tm.Process();
            }
            catch (Exception ex)
            {
                result = WrongMsg;
                WriteLog("CreateAspx \t" + ex.Message);
            }
            return result;
        }

        public string CreateAspxEdit(Table table, List<Column> columns)
        {
            string result = string.Empty;
            try
            {
                //筛选选择的              
                TemplateManager tm = TemplateManager.FromFile(string.Format("{0}{1}", GetTemplateDir(), Template.AspxEdit));
                tm.SetValue("table", table);
                tm.SetValue("columns", columns.Where(t => t.IsSelect).ToList());
                result = tm.Process();
            }
            catch (Exception ex)
            {
                result = WrongMsg;
                WriteLog("CreateAspxEdit \t" + ex.Message);
            }
            return result;
        }

        public string CreateAspxList(Table table, List<Column> columns)
        {
            string result = string.Empty;
            try
            {
                TemplateManager tm = TemplateManager.FromFile(string.Format("{0}{1}", GetTemplateDir(), Template.AspxList)); tm.SetValue("table", table);
                tm.SetValue("table", table);
                tm.SetValue("columns", columns.Where(t => t.IsSelect).ToList());
                result = tm.Process();
            }
            catch (Exception ex)
            {
                result = WrongMsg;
                WriteLog("CreateAspxList \t" + ex.Message);
            }
            return result;
        }

        public string CreateAspxQuery(Table table, List<Column> columns)
        {
            string result = string.Empty;
            try
            {
                TemplateManager tm = TemplateManager.FromFile(string.Format("{0}{1}", GetTemplateDir(), Template.AspxQuery));
                tm.SetValue("table", table);
                tm.SetValue("columns", columns.Where(t => t.IsWhere).ToList());
                result = tm.Process();
            }
            catch (Exception ex)
            {
                result = WrongMsg;
                WriteLog("CreateAspxQuery \t" + ex.Message);
            }
            return result;
        }

        public string CreateAspxCs(Table table)
        {
            string result = string.Empty;
            try
            {
                TemplateManager tm = TemplateManager.FromFile(string.Format("{0}{1}", GetTemplateDir(), Template.AspxCs));
                tm.SetValue("table", table);
                tm.SetValue("columns", GetColumns(table.Name));
                result = tm.Process();
            }
            catch (Exception ex)
            {
                result = WrongMsg;
                WriteLog("CreateAspxCs \t" + ex.Message);
            }
            return result;
        }

        public string CreateAspxCsEdit(Table table, List<Column> columns)
        {
            string result = string.Empty;
            try
            {
                TemplateManager tm = TemplateManager.FromFile(string.Format("{0}{1}", GetTemplateDir(), Template.AspxCsEdit));
                tm.SetValue("table", table);
                tm.SetValue("columns", columns.Where(t => t.IsSelect).ToList());
                result = tm.Process();
            }
            catch (Exception ex)
            {
                result = WrongMsg;
                WriteLog("CreateAspxCsEdit \t" + ex.Message);
            }
            return result;
        }

        public string CreateAspxCsQuery(Table table, List<Column> columns)
        {
            string result = string.Empty;
            try
            {
                TemplateManager tm = TemplateManager.FromFile(string.Format("{0}{1}", GetTemplateDir(), Template.AspxCsQuery));
                tm.SetValue("table", table);
                tm.SetValue("columns", columns.Where(t => t.IsWhere).ToList());
                result = tm.Process();
            }
            catch (Exception ex)
            {
                result = WrongMsg;
                WriteLog("CreateAspxCsQuery \t" + ex.Message);
            }
            return result;
        }

        public string CreateAspxCsSave(Table table, List<Column> columns)
        {
            string result = string.Empty;
            try
            {
                TemplateManager tm = TemplateManager.FromFile(string.Format("{0}{1}", GetTemplateDir(), Template.AspxCsSave));
                tm.SetValue("table", table);
                tm.SetValue("columns", columns.Where(t => t.IsSelect).ToList());
                result = tm.Process();
            }
            catch (Exception ex)
            {
                result = WrongMsg;
                WriteLog("CreateAspxCsSave \t" + ex.Message);
            }
            return result;
        }

        public string CreateBussinessImplement(Table table)
        {
            string result = string.Empty;
            try
            {
                TemplateManager tm = TemplateManager.FromFile(string.Format("{0}{1}", GetTemplateDir(), Template.BussinessImplement));
                tm.SetValue("table", table);
                tm.SetValue("columns", GetColumns(table.Name));
                result = tm.Process();
            }
            catch (Exception ex)
            {
                result = WrongMsg;
                WriteLog("CreateBussinessImplement \t" + ex.Message);
            }
            return result;
        }

        public string CreateServiceCmdObject(Table table, List<Column> columns)
        {
            string result = string.Empty;
            try
            {
                TemplateManager tm = TemplateManager.FromFile(string.Format("{0}{1}", GetTemplateDir(), Template.ServiceCmdObject));
                tm.SetValue("table", table);
                tm.SetValue("columns", columns.Where(t => t.IsWhere).ToList());
                result = tm.Process();
            }
            catch (Exception ex)
            {
                result = WrongMsg;
                WriteLog("CreateServiceCmdObject \t" + ex.Message);
            }
            return result;
        }

        public string CreateServicePageList(Table table, List<Column> columns)
        {
            string result = string.Empty;
            try
            {
                TemplateManager tm = TemplateManager.FromFile(string.Format("{0}{1}", GetTemplateDir(), Template.ServicePageList));
                tm.SetValue("table", table);
                tm.SetValue("columns", columns.Where(t => t.IsWhere).ToList());
                result = tm.Process();
            }
            catch (Exception ex)
            {
                result = WrongMsg;
                WriteLog("CreateServicePageList \t" + ex.Message);
            }
            return result;
        }

        #endregion

        #region IDataBase 成员


        public string CreateAspxInfo(Table table, List<Column> columns)
        {
            string result = string.Empty;
            try
            {
                TemplateManager tm = TemplateManager.FromFile(string.Format("{0}{1}", GetTemplateDir(), Template.AspxInfo));
                tm.SetValue("table", table);
                tm.SetValue("columns", columns.Where(t => t.IsSelect).ToList());
                result = tm.Process();
            }
            catch (Exception ex)
            {
                result = WrongMsg;
                WriteLog("CreateAspxInfo \t" + ex.Message);
            }
            return result;
        }

        public string CreateAspxCsInfo(Table table, List<Column> columns)
        {
            string result = string.Empty;
            try
            {
                TemplateManager tm = TemplateManager.FromFile(string.Format("{0}{1}", GetTemplateDir(), Template.AspxCsInfo));
                tm.SetValue("table", table);
                tm.SetValue("columns", columns.Where(t => t.IsSelect).ToList());
                result = tm.Process();
            }
            catch (Exception ex)
            {
                result = WrongMsg;
                WriteLog("CreateAspxCsInfo \t" + ex.Message);
            }
            return result;
        }

        #endregion



        #region IDataBase 成员


        public string CreateDataContract(Table table, List<Column> columns)
        {
            string result = string.Empty;
            try
            {
                TemplateManager tm = TemplateManager.FromFile(string.Format("{0}{1}", GetTemplateDir(), Template.Datacontract));
                tm.SetValue("table", table);
                tm.SetValue("columns", columns);
                result = tm.Process();
            }
            catch (Exception ex)
            {
                result = WrongMsg;
                WriteLog("CreateDataContract \t" + ex.Message);
            }
            return result;
        }

        public string CreateDataExchange(Table table, List<Column> columns)
        {
            string result = string.Empty;
            try
            {
                TemplateManager tm = TemplateManager.FromFile(string.Format("{0}{1}", GetTemplateDir(), Template.Dataexchange));
                tm.SetValue("table", table);
                tm.SetValue("columns", columns);
                result = tm.Process();
            }
            catch (Exception ex)
            {
                result = WrongMsg;
                WriteLog("CreateDataExchange \t" + ex.Message);
            }
            return result;
        }

        #endregion



        #region IDataBase 成员

        /// <summary>
        /// 获取文件名称
        /// </summary>
        /// <param name="tableName"></param>
        /// <param name="type"></param>
        /// <returns></returns>
        public string GetCodeFileName(string tableName, PageType type)
        {
            string fileName = string.Empty;
            switch (type)
            {
                case PageType.Web:
                    fileName = string.Format("{0}Manager", Utils.GetDTOName(tableName));
                    break;              
                case PageType.SqlServerBussinessImplement:
                    fileName = string.Format("{0}Bussiness", Utils.GetDTOName(tableName));
                    break;
                case PageType.SqlServerDataExchage:
                    fileName = string.Format("{0}Utils", Utils.GetDTOName(tableName));
                    break;
                case PageType.ServiceImplete:
                    fileName = string.Format("{0}Service", Utils.GetDTOName(tableName));
                    break;
                case PageType.ServiceContract:
                    fileName = string.Format("I{0}Service", Utils.GetDTOName(tableName));
                    break;               
                default:
                    fileName = string.Format("{0}", Utils.GetDTOName(tableName));
                    break;
            }
            return fileName;
        }

        #endregion


        #region IDataBase 成员
        public string GetBussinessName()
        {
            return Utils.GetBussinessName();
        }

        #endregion

        #region IDataBase 成员


        public List<CodeModel> GetModels()
        {
            return new List<CodeModel>();
        }

        #endregion

        #region IDataBase 成员


        public string CreateAspxDesignerCs(Table table, List<Column> columns)
        {
            string result = string.Empty;
            try
            {
                TemplateManager tm = TemplateManager.FromFile(string.Format("{0}{1}", GetTemplateDir(), Template.AspxDesignerCs));
                tm.SetValue("table", table);
                tm.SetValue("columns", columns);
                result = tm.Process();
            }
            catch (Exception ex)
            {
                result = WrongMsg;
                WriteLog("CreateAspxDesignerCs \t" + ex.Message);
            }
            return result;
        }

        public string CreateServiceContract(Table table, List<Column> columns)
        {
            string result = string.Empty;
            try
            {
                TemplateManager tm = TemplateManager.FromFile(string.Format("{0}{1}", GetTemplateDir(), Template.ServiceContract));
                tm.SetValue("table", table);
                tm.SetValue("columns", columns);
                result = tm.Process();
            }
            catch (Exception ex)
            {
                result = WrongMsg;
                WriteLog("CreateServiceContract \t" + ex.Message);
            }
            return result;
        }

        public string CreateServiceImplement(Table table, List<Column> columns)
        {
            string result = string.Empty;
            try
            {
                TemplateManager tm = TemplateManager.FromFile(string.Format("{0}{1}", GetTemplateDir(), Template.ServiceImplement));
                tm.SetValue("table", table);
                tm.SetValue("columns", columns);
                result = tm.Process();
            }
            catch (Exception ex)
            {
                result = WrongMsg;
                WriteLog("CreateServiceImplement \t" + ex.Message);
            }
            return result;
        }

        public string CreateCoreService(Table table)
        {
            string result = string.Empty;
            try
            {
                TemplateManager tm = TemplateManager.FromFile(string.Format("{0}{1}", GetTemplateDir(), Template.CoreService));
                tm.SetValue("table", table);
                result = tm.Process();
            }
            catch (Exception ex)
            {
                result = WrongMsg;
                WriteLog("CreateCoreService \t" + ex.Message);
            }
            return result;
        }

        public string CreateIocConfig(Table table)
        {
            string result = string.Empty;
            try
            {
                TemplateManager tm = TemplateManager.FromFile(string.Format("{0}{1}", GetTemplateDir(), Template.IocConfig));
                tm.SetValue("table", table);
                result = tm.Process();
            }
            catch (Exception ex)
            {
                result = WrongMsg;
                WriteLog("CreateIocConfig \t" + ex.Message);
            }
            return result;
        }

        #endregion
    }
}
